<!--商品管理-->
<template>
  <div id="product" class="app-container flex-row">
    <!-- 左侧树 -->
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:290px">
      <el-input v-model="searchValue" placeholder="请输入分类名称" style="margin: 10px 0;" />
      <el-tree
        ref="categoryTree"
        v-loading="treeLoading"
        class="common-el-tree tree-active"
        :data="categoryData"
        :props="defaultCategoryProps"
        node-key="id"
        :expand-on-click-node="false"
        :current-node-key="selectedDataId"
        :filter-node-method="onTreeFilter"
        @node-click="handleCategoryNodeClick">
        <span slot-scope="{ node}" class="custom-tree-node">
          <img v-if="node.data.level===2" :src="common.getFileView(node.data.categoryIcon)" style="width:22px;height:22px;margin-right: 5px;border-radius: 11px;" @error="handleImageError">
          <span class="text">{{ node.label }}</span>
        </span>
      </el-tree>
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.name" clearable placeholder="请输入商品名称" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.sn" clearable placeholder="请输入商品SN" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="listQuery.isSale" clearable filterable placeholder="请选择商品状态">
              <el-option label="全部" value="" />
              <el-option label="在售" value="1" />
              <el-option label="下架" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="60" />
          <el-table-column align="center" prop="id" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="图片" prop="smallImage" width="80" align="center">
            <template slot-scope="scope">
              <img :src="common.getFileView(scope.row.smallImage)" style="width: 46px;height: 46px;" @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column label="SN" prop="sn" width="130" show-overflow-tooltip />
          <el-table-column label="商品名称" prop="name" min-width="300" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>
                {{ scope.row.name }}
              </div>
              <div>
                {{ scope.row._fullCategoryName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="售价" prop="price" width="120">
            <template slot-scope="scope">
              <span class="color-danger">{{ scope.row.price | formatPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成本价" prop="costPrice" width="120">
            <template slot-scope="scope">
              <span class="color-danger">{{ scope.row.costPrice | formatPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="isSale" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.isSale===1" class="color-primary">在售</span>
              <span v-if="scope.row.isSale===0" class="color-danger">下架</span>
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="totalInventory" width="120" sortable>
            <template slot-scope="scope">{{ scope.row.totalInventory }}{{ scope.row.unit }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <button-option v-if="scope.row.isSale===1" icon="el-icon-download" skin="warning" title="下架" @click="productRemoveShelves(scope.row)" />
              <button-option v-if="scope.row.isSale===0" icon="el-icon-upload2" skin="primary" title="上架" @click="productPutShelves(scope.row)" />
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      searchValue: '',
      defaultCategoryProps: {
        children: 'children',
        label: 'categoryName'
      },
      categoryData: [],
      treeLoading: false,
      optionButton: false,
      selectedDataId: '',
      selectedTreeData: {},
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        name: '',
        sn: '',
        isSale: '',
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: []
    }
  },
  watch: {
    searchValue: function(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    this.categoryTree()
  },
  methods: {
    async categoryTree() {
      this.treeLoading = true
      this.categoryData = []
      const response = await this.$store.dispatch('productCategoryTreeTable', { })
      this.categoryData = [{
        id: 0,
        treeNumber: '',
        categoryName: '全部'
      }, ...response]
      if (this.categoryData.length > 0) {
        var selectId = this.categoryData[0].id
        this.$refs.categoryTree.setCheckedKeys([selectId])
        this.$nextTick(() => {
          this.handleCategoryNodeClick(this.categoryData[0], this.$refs.categoryTree.getNode(selectId))
        })
      }
      this.treeLoading = false
    },
    onTreeFilter(value, data) {
      if (!value) return true
      return data[this.defaultCategoryProps.filter] ? data[this.defaultCategoryProps.label].indexOf(value) !== -1 || data[this.defaultCategoryProps.filter].indexOf(value.toUpperCase()) !== -1 : data[this.defaultCategoryProps.label].indexOf(value) !== -1
    },
    // 单击节点
    handleCategoryNodeClick(data, node) {
      this.selectedTreeData = data
      this.selectedDataId = data.id
      this.$nextTick(() => {
        this.$refs.categoryTree.setCurrentKey(data.id)
      })
      this.listQuery = {
        ...this.listQuery,
        name: '',
        sn: '',
        isSale: '',
        treeNumber: data.treeNumber
      }
      this.fetchData()
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        name: '',
        sn: '',
        isSale: '',
        sort: this.common.SORT_DEFAULT
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('productPageV2', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.$router.push({ name: 'productCreate', query: { }})
    },
    /* 编辑*/
    handleUpdate(row) {
      this.$router.push({ name: 'productCreate', query: { id: row.id }})
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('productRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    productPutShelves(row) {
      this.$confirm(`您确定要上架商品${row.name}, 是否继续?'`, '上架提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('productPutShelves', row.id).then(response => {
          this.handleReset()
          this.$modal.msgSuccess('上架成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    productRemoveShelves(row) {
      this.$confirm(`您确定要下架商品${row.name}, 是否继续?'`, '下架提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('productRemoveShelves', row.id).then(response => {
          this.handleReset()
          this.$modal.msgSuccess('下架成功')
        }).catch(() => {})
      }).catch(() => { })
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
